class Solution {
public:
    struct Compare {
        bool operator()(const vector<int>& v1, const vector<int>& v2) {
            if (v1[0] == v2[0]) {
                return v1[1] < v2[1];
            }
            return v1[0] < v2[0];
        }
    };
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        vector<vector<int>> ans;
        sort(intervals.begin(), intervals.end(), Compare());
        int start = intervals[0][0], end = intervals[0][1];
        for (int i = 1; i < intervals.size(); i++) {
            if (intervals[i][0] > end) {
                ans.push_back(vector<int>({start, end}));
                start = intervals[i][0];
                end = intervals[i][1];
            } else if (end < intervals[i][1]) {
                end = intervals[i][1];
            }
        }
        ans.push_back(vector<int>({start, end}));
        return ans;
    }
};